package io.gitee.kotle.android.library.websocket.impl

import io.gitee.kotle.android.library.websocket.IWebSocket
import io.gitee.kotle.android.utils.postMainHandler

/**
 *
 * 描述：
 *
 * @author jiale.wei
 *
 * 创建时间：2022/8/10 15:38
 *
 */
abstract class BaseWebSocket : IWebSocket {

    private val _listeners = mutableListOf<IWebSocket.Listener>()

    final override val listeners: List<IWebSocket.Listener>
        get() = _listeners

    final override fun addListener(l: IWebSocket.Listener?) {
        l ?: return
        if (!_listeners.contains(l)) {
            _listeners.add(l)
        }
    }

    final override fun removeListener(l: IWebSocket.Listener?) {
        _listeners.remove(l)
    }

    fun eachListener(block: (IWebSocket.Listener) -> Unit) {
        listeners.toList().forEach {
            postMainHandler {
                block.invoke(it)
            }
        }
    }
}